//
//  WBTitleButton.swift
//  DLSwift微博
//
//  Created by 丁浪涛 on 2016/11/17.
//  Copyright © 2016年 丁浪涛. All rights reserved.
//

import UIKit

class WBTitleButton: UIButton {
     //重载构造函数
    //如果 title为nil 显示首页

    init(title:String?) {
        super.init(frame: CGRect())
        if title == nil {
          setTitle("首页", for: [])
        }
        else
        {
            setTitle(title! + " ", for: [])
            setImage(  UIImage(named: "navigationbar_arrow_down"), for: [])
            setImage(  UIImage(named: "navigationbar_arrow_up"), for: .selected)
        
        }
        titleLabel?.font = UIFont.boldSystemFont(ofSize: 17)
        setTitleColor(UIColor.darkGray, for: [])
        sizeToFit()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //重新布局子视图
    override func layoutSubviews() {
        super.layoutSubviews()
        
        guard let titleLabel = titleLabel,
              let  imageView = imageView
        else {
            return
        }
        //将titleLabel 向左移动imageView的宽度
        //将imageView 向右移动titleLabel的宽度
         print("顶部按钮布局 \n \(titleLabel) \n \(imageView)")
        if titleLabel.frame.origin.x > 2
        {
            titleLabel.frame = titleLabel.frame.offsetBy(dx: -imageView.bounds.width, dy: 0)
            imageView.frame = imageView.frame.offsetBy(dx: titleLabel.bounds.width, dy: 0)
        }
    }
}
